import React, {
  useEffect, useMemo, useRef, useState,
} from 'react';
import {
  DataSet, Form, TextField, SelectBox, Icon, useModal, Modal as ModalInstance, Button,
} from 'choerodon-ui/pro';
import { mailApi, mailApiConfig, axios } from '@choerodon/master';
import { inject } from 'mobx-react';
import { Upload } from 'choerodon-ui';
import { observer } from 'mobx-react-lite';
import Cropper from 'react-cropper';
import { pick } from 'lodash';
import classnames from 'classnames';
import FormDs from '../stores/formDataSet';
import ChoerodonEditor from '@/components/choerodonEditor';
import 'cropperjs/dist/cropper.css';
import './index.less';

export interface Props {
  modal: any
  // eslint-disable-next-line react/require-default-props
  recordData?: any
  refresh: () => void
  prefixCls: string
  level: 'site' | 'organization'
}
interface ITemplate {
  custom: boolean
  logo: string
  slogan: string
  footer: string
}

const modalkey1 = ModalInstance.key();

const CropModal = (p: any) => {
  // HTMLImageElement
  const cropperRef = useRef<any>(null);
  const {
    modal, url, handleCrop, aspectRatio,
  } = p;

  const handleZoomIn = () => {
    const cropper = cropperRef?.current?.cropper;
    cropper.zoom(0.1);
  };

  const handleZoomout = () => {
    const cropper = cropperRef?.current?.cropper;
    cropper.zoom(-0.1);
  };

  const handleRotate = () => {
    const cropper = cropperRef?.current?.cropper;
    cropper.rotate(90);
  };

  const handleOk = () => {
    const cropper = cropperRef?.current?.cropper;
    if (typeof cropper.getCroppedCanvas() === 'undefined') {
      return;
    }

    handleCrop(cropper.getCroppedCanvas().toDataURL());
  };

  modal.handleOk(handleOk);

  return (
    <div className={`${p.prefixCls}-container-Cropper`}>
      <Cropper
        style={{ height: 420, width: 702 }}
        aspectRatio={aspectRatio}
        guides={false}
        src={url}
        ref={cropperRef}
        viewMode={1}
        dragMode="move"
        cropBoxMovable={false}
      // movable={false}
      />
      <div className="button-container">
        <Button icon="zoom_in" onClick={handleZoomIn} />
        <Button icon="zoom_out" onClick={handleZoomout} />
        <Button icon="play_90" onClick={handleRotate} />
        <Button>1:1</Button>
      </div>
    </div>

  );
};

let orgCurrentData: Partial<ITemplate> = {};
let orgExcludeCurrentData: Partial<ITemplate> = {};
let orgOriginCustom: boolean;

const StatusOperation = (props: Props) => {
  const {
    // @ts-ignore
    modal, recordData, refresh, prefixCls, level, AppState: { currentMenuType: { organizationId } },
    // @ts-ignore
    AppState: { getUserId },
  } = props;
  const Modal = useModal();

  const [orgLogo, setOrgLogo] = useState('');

  const reqOrgExcludeCurrentData = async (isCustom: boolean) => {
    const configRes = isCustom ? await mailApi.siteGetMailTemplateConfig() : await mailApi.orgGetMailTemplateConfig();
    const previewRes = await mailApi.mailTemplatePreview({
      logo: configRes.logo,
      slogan: configRes.slogan,
      footer: configRes.footer,
    });
    configRes.preview = previewRes;
    orgExcludeCurrentData = configRes;
  };

  const formDs = useMemo(() => {
    const ds = new DataSet(FormDs({ level, mailApiConfig }));
    if (recordData) {
      const data = recordData?.toData();
      if (!data.custom) {
        data.custom = false;
      }
      orgOriginCustom = data.custom;
      if (level === 'organization') {
        orgCurrentData = data;
        reqOrgExcludeCurrentData(data.custom);
      }
      ds.loadData([data]);
    }
    return ds;
  }, []);

  useEffect(() => {
    refreshPreview();
    getShowReplaceLogoBtnVisible();
  }, []);

  useEffect(() => {
    if (level === 'organization') {
      const data: any = formDs?.toData()[0];
      if (!data.custom) {
        data.custom = false;
      }
      orgOriginCustom === formDs?.current?.get('custom') ? orgCurrentData = data
        : orgExcludeCurrentData = data;
    }
  }, [formDs?.toData()]);

  const getShowReplaceLogoBtnVisible = async () => {
    if (level === 'organization') {
      const res = await axios.get(`/cbase/choerodon/v1/organizations/${organizationId}/org_level`);
      if (res?.tenantConfigVO?.imageUrl) {
        setOrgLogo(res?.tenantConfigVO?.imageUrl);
      }
    }
  };

  const handleCustomChange = (value: boolean) => {
    if (orgOriginCustom !== value) {
      orgExcludeCurrentData.custom = value;
      formDs?.loadData([orgExcludeCurrentData]);
    } else {
      orgCurrentData.custom = value;
      formDs?.loadData([orgCurrentData]);
    }
  };

  const handleCrop = async (dataUrl: any) => {
    function dataURLtoFile(dataurl: any, filename: string) {
      const arr = dataurl.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      // eslint-disable-next-line no-plusplus
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    }

    const file = dataURLtoFile(dataUrl, `${new Date().getTime()}${getUserId}logo`);
    const data = new FormData();
    data.append('file', file);

    const res = level === 'site' ? await axios.post('/hfle/v1/files/multipart?bucketName=iam-service', data)
      : await axios.post(`/hfle/v1/${organizationId}/files/multipart?bucketName=iam-service`, data);
    formDs?.current?.set('logo', res);
  };

  const beforeUpload = (imgFile: any) => {
    const image = new Image();
    image.onload = function () {
      const { width } = image;
      const { height } = image;
      Modal.open({
        key: modalkey1,
        title: '编辑图片',
        children: <CropModal url={url} prefixCls={prefixCls} handleCrop={handleCrop} aspectRatio={width / height} />,
        style: {
          width: 750,
        },
      });
    };
    const url = URL.createObjectURL(imgFile);
    image.src = url;
    return false;
  };

  const handleDeleteLogo = () => {
    formDs?.current?.set('logo', null);
  };

  const refreshPreview = async () => {
    const res = await mailApi.mailTemplatePreview({
      logo: formDs?.current?.get('logo'),
      slogan: formDs?.current?.get('slogan'),
      footer: formDs?.current?.get('footer'),
    });
    formDs?.current?.set('preview', res);
  };

  const handleChangeLogoToOrg = () => {
    formDs?.current?.set('logo', orgLogo);
  };

  const handleOk = async () => {
    const postObj = pick(formDs?.current?.toData(), ['custom', 'logo', 'slogan', 'footer']);
    try {
      level === 'site' ? await mailApi.siteCreateOrUpdateMailTemplate(postObj) : await mailApi.orgCreateOrUpdateMailTemplate(postObj);
      refresh && refresh();
      return true;
    } catch (error) {
      return false;
    }
  };

  const getDisable = () => {
    if (level === 'site') {
      return false;
    }
    return formDs?.current?.get('custom') === false;
  };

  const logoContainerCls = classnames({
    'logo-container': true,
    'logo-container-disable': getDisable(),
  });

  modal.handleOk(handleOk);

  return (
    <div className={`${prefixCls}-operation-form-content`}>
      <Form dataSet={formDs}>
        {
          level === 'organization'
          && (
            <SelectBox
              name="custom"
              onChange={handleCustomChange}
              label={(
                <>
                  <span>邮件模板设置</span>
                </>
              )}
            >
              <SelectBox.Option value={false}>沿用平台邮件模板</SelectBox.Option>
              <SelectBox.Option value>自定义邮件模板</SelectBox.Option>
            </SelectBox>
          )
        }
      </Form>
      <div className="row-item row-one">
        <div className="row-left-label">
          邮件Logo
        </div>
        <div className="right row-right-content">
          <div className="row-right-content-left">
            <div className={logoContainerCls}>
              <img className="img-logo" src={formDs?.current?.get('logo')} alt="" />
              {
                !getDisable() && (
                  <>
                    <div role="none" className="mask">
                      <Upload accept="image/*" showUploadList={false} beforeUpload={beforeUpload}>
                        <Icon type="photo_camera" />
                      </Upload>
                      {
                      formDs?.current?.get('logo') && <Icon onClick={handleDeleteLogo} type="delete_forever" />
                      }
                    </div>
                  </>
                )
              }
            </div>
            <div className="row-right-content-left-right" role="none" onClick={handleChangeLogoToOrg}>
              {
                level === 'organization' && orgLogo && formDs?.current?.get('custom') && '替换为组织Logo'
              }
            </div>
          </div>

          <Form dataSet={formDs}>
            <TextField className="field-slogan" name="slogan" disabled={getDisable()} showLengthInfo />
          </Form>
        </div>
      </div>

      <div className="row-item row-two">
        <div className="row-left-label">
          邮件页脚
        </div>

        <div className="row-right-content">
          <ChoerodonEditor
            disabled={getDisable()}
            value={formDs?.current?.get('footer')}
            onChange={(value: any) => {
              formDs?.current?.set('footer', value);
            }}
            defaultShowCode={false}
            textHeaderButton
          />
        </div>
      </div>

      <div className="row-item row-three">
        <div className="row-left-label">
          预览
        </div>
        <div className="row-right-content preview-content">
          <div dangerouslySetInnerHTML={{ __html: formDs?.current?.get('preview') }} />
          {
            !getDisable() && <Button icon="refresh" className="btn-refresh" onClick={refreshPreview}>刷新</Button>
          }
        </div>
      </div>
    </div>
  );
};

export default inject('AppState')(observer(StatusOperation));
